import axios from "axios";

const APP_SRC = "js/app.";

/**
 * 生产环境下主动检查代码更新
 * @returns {Promise<boolean>}
 */
export default async function (): Promise<boolean> {
  if (process.env.NODE_ENV === "production") {
    try {
      const localAppScriptElem = document.body.querySelector('script[src*="' + APP_SRC + '"]');
      if (localAppScriptElem) {
        const res = await axios.get(window.location.pathname + "?t=" + +new Date());
        const localAppSrc = localAppScriptElem.getAttribute("src");
        const appSrcIndex = res.data.lastIndexOf(APP_SRC) - 99;
        if (localAppSrc) {
          return res.data.substr(appSrcIndex).indexOf(localAppSrc) === -1; // 未匹配到文件的hash，说明服务端的文件已经变更
        }
      }
    } catch (e) {
      console.log(e);
    }
  }
  return false;
}
